#include "pdf_to_word_dialog.h"
#include "ui_pdf_to_word_dialog.h"
#include <QFileDialog>
#include <QFile>
#include <QDebug>
#include <QCoreApplication>
#include <Windows.h>  // 包含Windows API头文件
#include "selectpdfform.h"

PDF_To_Word_Dialog::PDF_To_Word_Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::PDF_To_Word_Dialog)
{
    ui->setupUi(this);
    // 设置无边框
    this->setWindowFlags(Qt::FramelessWindowHint);
    setFixedSize(854, 531);
    m_pVBoxLayout=new QVBoxLayout();
    ui->widget_list->setLayout(m_pVBoxLayout);
    m_pVBoxLayout->addStretch();

    // 初始化进程对象
     pythonExeProcess_ = new QProcess(this);

     // 设置进程启动参数（Windows平台）
#ifdef Q_OS_WIN
        // 设置隐藏窗口标志
        pythonExeProcess_->setCreateProcessArgumentsModifier(
            [](QProcess::CreateProcessArguments *args) {
                // 隐藏窗口并在后台运行
                args->flags |= CREATE_NO_WINDOW;
                args->startupInfo->dwFlags |= STARTF_USESHOWWINDOW;
                args->startupInfo->wShowWindow = SW_HIDE;
            }
        );
#endif

     // 连接信号槽
     connect(pythonExeProcess_, &QProcess::readyReadStandardOutput,
             this, &PDF_To_Word_Dialog::readProcessOutput);
//     connect(pythonExeProcess_, &QProcess::finished,
//             this, &PDF_To_Word_Dialog::processFinished);

     connect(pythonExeProcess_, SIGNAL(finished(int, QProcess::ExitStatus)),
             this, SLOT(processFinished(int, QProcess::ExitStatus)));

     connect(pythonExeProcess_, &QProcess::errorOccurred,
             this, &PDF_To_Word_Dialog::processErrorOccurred);

   // ui->pdfLbl->setPixmap(QPixmap(":/images/Pdf.png"));
    ui->widget_list->hide();
    ui->pushButton_export->setEnabled(false);

    ui->tabWidget->setTabEnabled(1, false);
    ui->tabWidget->setTabEnabled(2, false);
    ui->tabWidget->setTabEnabled(3, false);
    ui->tabWidget->setTabEnabled(4, false);
    ui->tabWidget->setTabEnabled(5, false);
}

PDF_To_Word_Dialog::~PDF_To_Word_Dialog()
{
    delete ui;
    if(pythonExeProcess_){
        if (pythonExeProcess_->state() == QProcess::Running) {
            pythonExeProcess_->kill();
        }
        delete pythonExeProcess_;
    }
}

void PDF_To_Word_Dialog::on_closeBtn_clicked()
{
    close();
}

void PDF_To_Word_Dialog::on_minBtn_clicked()
{
    showMinimized();
}

void PDF_To_Word_Dialog::on_pushButton_add_file_clicked()
{
    QString szPath = qApp->applicationDirPath() + "/Solution/ScriptFile/MoveScript/";
    QString openFile = QFileDialog::getOpenFileName(nullptr, tr("Load PDF file"), szPath, QString("PDF(*.pdf)"));
    qDebug()<<openFile;
    if (openFile.isEmpty()|| ""==openFile)
    {
        qDebug()<<"openFile.isEmpty()";
        return;
    }
     QFile file(openFile);
    if(!file.open(QIODevice::ReadOnly | QIODevice::Text)){
        qDebug()<<"file.open failed";
        return;
    }
    file.close();
    qDebug()<<openFile;


    if(m_pVBoxLayout){
        int id=m_pVBoxLayout->count()-1;
        qDebug()<<"set id"<<id;
        auto pSelectPdfForm=new SelectPdfForm(id,ui->widget_list);
        pSelectPdfForm->SetFileName(openFile);
         m_pVBoxLayout->insertWidget(id,pSelectPdfForm);

         //切换状态
         connect(this,&PDF_To_Word_Dialog::sig_changeState,pSelectPdfForm,&SelectPdfForm::slot_changeState);
         //清除
         connect(pSelectPdfForm,&SelectPdfForm::sig_clearRecord,this,[=](int id){
             if(m_pVBoxLayout){
                 int count=m_pVBoxLayout->count();
                  qDebug()<<"clear id:"<<id<<",count:"<<count;
                 if(count >0 && id< count){
                    // qDebug()<<"clear id   "<<id;
                     QLayoutItem *item = m_pVBoxLayout->itemAt(id);
                        if (item->widget()) {
                            auto widget = item->widget();
                            m_pVBoxLayout->removeWidget(widget);
                            delete widget;
                            qDebug()<<"clear id:"<<id;
                        }
                 }

             }
             //qDebug() << m_pVBoxLayout->count();
             if(m_pVBoxLayout->count() <=1 )
             {
                 ui->widget_list->hide();
                 ui->pushButton_export->setEnabled(false);
                 ui->addFileWgt->show();
             }
         });
    }
    ui->addFileWgt->hide();
    ui->pushButton_export->setEnabled(true);
    ui->widget_list->show();
}


//转换
void PDF_To_Word_Dialog::on_pushButton_export_clicked()
{
    if(!m_pVBoxLayout){
        return;
    }

    int count=m_pVBoxLayout->count();
    for(int i=0;i< count-1;i++){
        QLayoutItem *item = m_pVBoxLayout->itemAt(i);
           if (item->widget()) {
               auto widget = item->widget();
              SelectPdfForm* pForm=static_cast<SelectPdfForm*>(widget);
              if(pForm->isChecked()){
                  QString fileName=pForm->GetFileName();
                  qDebug()<<"fileName:"<<fileName;

                  id_currentRunning_=i;
                   emit sig_changeState(id_currentRunning_,QString("正在执行..."));

                  //调用
                  QFileInfo fileInfo(fileName);
                  QString dstPath=fileInfo.absolutePath();
                  qDebug()<<"dstPath:"<<dstPath;
                   bool ret=CreateWordFile(fileName,dstPath);
                   if(!ret)
                       qDebug()<<"CreateWordFile Failed:"<<ret;
                   else
                       qDebug()<<"CreateWordFile Success:"<<ret;

              }

        }
    }
}

 bool PDF_To_Word_Dialog::CreateWordFile(const QString& pdfPath,const QString& outPath)
 {

     // Python生成的exe路径
     QString appPath=qApp->applicationDirPath();

     QString exePath = appPath+"/lib/pdftoword.exe";;
    qDebug()<<"exePath:"<<exePath;

    // 传递给exe的参数（可选）
    QStringList arguments;
    arguments << pdfPath << outPath;

    // 启动进程
    pythonExeProcess_->start(exePath, arguments);

    // 检查是否成功启动
    if (!pythonExeProcess_->waitForStarted()) {
         qDebug()<<"start Process Failed:"<<pythonExeProcess_->errorString();
         return false;
    }

     return true;
 }

 void PDF_To_Word_Dialog::readProcessOutput()
 {
     // 读取标准输出
        QByteArray output = pythonExeProcess_->readAllStandardOutput();
        if (!output.isEmpty()) {
            //ui->outputTextEdit->append("cout: " + QString(output));
             qDebug()<<"cout:"<<QString(output);
        }

        // 读取错误输出
        QByteArray errorOutput = pythonExeProcess_->readAllStandardError();
        if (!errorOutput.isEmpty()) {
            //ui->outputTextEdit->append("error: " + QString(errorOutput));
             qDebug()<<"error:"<<QString(errorOutput);
        }
 }

 void PDF_To_Word_Dialog::processFinished(int exitCode, QProcess::ExitStatus exitStatus)
 {
     if (exitStatus == QProcess::NormalExit) {
             //ui->outputTextEdit->append("[" + QDateTime::currentDateTime().toString() + "] 进程正常结束，退出码: " + QString::number(exitCode));
             qDebug()<<"exit ok:"<<QString::number(exitCode);
             emit sig_changeState(id_currentRunning_,"转换完成");
         } else {
             //ui->outputTextEdit->append("[" + QDateTime::currentDateTime().toString() + "] 进程异常结束，退出码: " + QString::number(exitCode));
             qDebug()<<"exit error:"<<QString::number(exitCode);
             emit sig_changeState(id_currentRunning_,"转换失败");
         }
 }

 void PDF_To_Word_Dialog::processErrorOccurred(QProcess::ProcessError error)
 {
     QString errorMsg;
        switch (error) {
            case QProcess::FailedToStart:
                errorMsg = "FailedToStart 进程启动失败 - 可能是因为可执行文件不存在或权限不足";
                break;
            case QProcess::Crashed:
                errorMsg = "Crashed 进程崩溃";
                break;
            case QProcess::Timedout:
                errorMsg = "Timedout 进程超时";
                break;
            case QProcess::ReadError:
                errorMsg = "ReadError 读取错误";
                break;
            case QProcess::WriteError:
                errorMsg = "WriteError 写入错误";
                break;
            case QProcess::UnknownError:
            default:
                errorMsg = "UnknownError 未知错误";
                break;
        }

        qDebug()<<"processErrorOccurred:"<<errorMsg;
 }

